<?php

namespace App\Http\Controllers\Api\Train;

use App\Http\Controllers\Controller;
use App\Http\Resources\Train\Screen\ArrivingResource;
use App\Http\Resources\Train\Screen\WaitingResource;
use App\Trip\Train\Providers\Ctrip\TrainQuery;
use App\Trip\Train\TrainQueryFromToData;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Http\Request;

class ScreenController extends Controller
{


    /**
     * @throws GuzzleException
     * @throws BindingResolutionException
     * @throws Exception
     */
    public function waiting(Request $request)
    {
        $query = new TrainQuery();
        $code  = $this->screen_code($request);
        $res   = $query->queryScreen($code, 0);
        return $this->success('', WaitingResource::collection($res));
    }

    /**
     * @param Request $request
     * @return mixed|string
     * @throws Exception
     */
    private function screen_code(Request $request)
    {
        $type = $request->input('type', 0);
        $code = $request->input('station_code', 'WAR');
        if ($type >= 0) {
            $tq    = new TrainQueryFromToData([
                'type' => $type,
                'code' => $code,
            ]);
            $codes = $tq->parseData2StationCodes();

            if (!empty($codes)) {
                $code = $codes[0];
            }

        }
        if (!$code) {
            throw new Exception('大屏站点不存在', 404);
        }
        return $code;
    }

    /**
     * @throws GuzzleException
     * @throws BindingResolutionException
     * @throws Exception
     */
    public function arriving(Request $request)
    {
        $query = new TrainQuery();
        $code  = $this->screen_code($request);
        $res   = $query->queryScreen($code, 1);
        return $this->success('', ArrivingResource::collection(collect($res)));
    }
}
